package com.ppc.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ppc.context.BaseContext;
import com.ppc.dto.EmployerTaskDTO;
import com.ppc.dto.EmployerTaskPageQueryDTO;
import com.ppc.entity.Claim;
import com.ppc.entity.Employer;
import com.ppc.entity.Recording;
import com.ppc.entity.Requirement;
import com.ppc.entity.TempTask;
import com.ppc.entity.Worker;
import com.ppc.exception.BaseException;
import com.ppc.exception.DeletionNotAllowedException;
import com.ppc.mapper.employer.EmployerClaimMapper;
import com.ppc.mapper.employer.EmployerTaskMapper;
import com.ppc.result.PageResult;
import com.ppc.service.EmployerTaskService;
import com.ppc.vo.EmployerConfirm;
import com.ppc.vo.EmployerTaskQueryVO;
import com.ppc.vo.EmployerWorkerTaskVO;
import com.ppc.vo.TaskDetail;
import com.ppc.vo.WorkerHandInResultVO;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 雇主订单实现
 *
 * @author LENOVO
 * @date 2023/12/20
 */
@Service
public class EmployerTaskServiceImpl implements EmployerTaskService {

  @Autowired
  private EmployerTaskMapper employerTaskMapper;

  @Autowired
  private EmployerClaimMapper employerClaimMapper;

  /**
   * 分页查询
   *
   * @param employerTaskPageQueryDTO
   * @return
   */
  @Override
  public PageResult taskPageQuery(EmployerTaskPageQueryDTO employerTaskPageQueryDTO) {
    Long userId=BaseContext.getCurrentId();
    Long employerId=employerTaskMapper.getEmployerIdByUserId(userId);
    //开始分页查询
    PageHelper.startPage(employerTaskPageQueryDTO.getPage(),
        employerTaskPageQueryDTO.getPageSize());

    Page<EmployerTaskQueryVO> page = employerTaskMapper.taskPageQuery(
        employerTaskPageQueryDTO.getTaskStatus(),employerTaskPageQueryDTO.getRequireTitle(),
        employerId);

    long total = page.getTotal();
    List<EmployerTaskQueryVO> records = page.getResult();

    return new PageResult(total, records);
  }

  /**
   * 雇主查看订单详细信息
   *
   * @param taskId
   * @return
   */
  @Override
  public TaskDetail checkTaskDetail(Long taskId) {
    TaskDetail taskDetail = employerTaskMapper.checkTaskDetail(taskId);
    return taskDetail;
  }

  /**
   * 雇主查看员工提交结果
   *
   * @param taskId
   * @return
   */
  @Override
  public EmployerWorkerTaskVO checkWorkerTask(Long taskId) {
    List<WorkerHandInResultVO> workerHandInResultList = employerTaskMapper.checkWorkerTask(taskId);
    EmployerWorkerTaskVO employerWorkerTaskVO = EmployerWorkerTaskVO.builder()
        .workerHandInResultList(workerHandInResultList)
        .build();
    return employerWorkerTaskVO;
  }

  /**
   * 更新订单状态
   *
   * @param taskId
   */
  public void updateTaskStatus(Long taskId) {
    int taskStatus = 50 + employerTaskMapper.getTaskStatusById(taskId);
    employerTaskMapper.updateTaskStatus(taskId, taskStatus);
  }

  /**
   * 雇主修改订单
   *
   * @param employerTaskDTO
   * @return
   */
  public void updateTask(EmployerTaskDTO employerTaskDTO) {
    TempTask tempTask = TempTask.builder()
        .taskId(employerTaskDTO.getTaskId())
        .tempTaskStatus(0)
        .requireBroadDesc(employerTaskDTO.getRequireBroadDesc())
        .requireTitle(employerTaskDTO.getRequireTitle())
        .requireDetailDesc(employerTaskDTO.getRequireDetailDesc())
        .updateTime(LocalDateTime.now())
        .build();
    employerTaskMapper.createTempTask(tempTask);
  }

  /**
   * 创建申诉
   *
   * @param taskId
   * @param claimType
   * @param claimReason
   */
  @Override
  public void createClaim(Long taskId, Integer claimType, String claimReason) {
    Long notifyId=employerClaimMapper.queryNotifyId(taskId);
    Claim claim= Claim.builder().
            taskId(taskId).
            claimerId(BaseContext.getCurrentId()).
            claimerType(0).
            claimType(claimType).
            claimReason(claimReason).
            claimStartTime(LocalDateTime.now()).
            claimStatus(0).
            claimResult(2).
            notifyId(notifyId).
            build();
    //调用mapper层进行插入claim
    employerClaimMapper.insert(claim);
  }

  /**
   * 雇主确认订单
   *
   * @param taskId
   * @return
   */
  public void confirmTask(Long taskId) {
    EmployerConfirm employerConfirm = EmployerConfirm.builder()
        .taskId(taskId)
        .taskEndTime(LocalDateTime.now())
        .taskStatus(4)
        .build();
    Integer requireStatus=1;
    Requirement requirement=employerTaskMapper.getRequirementById(taskId);
    employerTaskMapper.confirm(employerConfirm);
    employerTaskMapper.setRequireStatus(requireStatus,requirement.getRequireId());
  }

  /**
   * 雇主钱包金额变化
   *
   * @param taskId
   */
  @Override
  public void updateEmployerWallet(Long taskId) {
    Employer employer = employerTaskMapper.getEmployerById(taskId);
    Requirement requirement = employerTaskMapper.getRequirementById(taskId);
    Float employerCount = employer.getEmployerCount() - requirement.getRequireAmount();
    if (employerCount < 0) {
      throw new DeletionNotAllowedException("余额不足，请充值");
    } else {
      Long employerId = employer.getEmployerId();
      int taskStatus = 1;
      employerTaskMapper.updateEmployerWallet(employerId, employerCount);
      employerTaskMapper.updateTaskStatus(taskId, taskStatus);
    }
  }

  /**
   * 工人钱包金额变化
   *
   * @param taskId
   */
  @Override
  public void updateWorkerWallet(Long taskId) {
    Worker worker = employerTaskMapper.getWorkerById(taskId);
    Requirement requirement = employerTaskMapper.getRequirementById(taskId);
    float workerCount = worker.getWorkerCount() + requirement.getRequireAmount();
    Long workerId = worker.getWorkerId();
    employerTaskMapper.updateWorkerWallet(workerId, workerCount);
  }

  /**
   * 雇主创建金额变化记录
   *
   * @param taskId
   */
  @Override
  public void createEmployerMoneyRecording(Long taskId) {
    Requirement requirement = employerTaskMapper.getRequirementById(taskId);
    Employer employer = employerTaskMapper.getEmployerById(taskId);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String localDateTime = formatter.format(LocalDateTime.now());
    Recording recording = Recording.builder()
        .recordingContent(
                localDateTime + " 发布" + " '" + requirement.getRequireTitle() + "' 订单,钱包金额-"
                + requirement.getRequireAmount() + "元")
        .recordingType(0)
        .userId(employer.getUserId())
        .build();
    employerTaskMapper.createMoneyRecording(recording);
  }

  /**
   * 工人创建金额变化记录
   *
   * @param taskId
   */
  @Override
  public void createWorkerMoneyRecording(Long taskId) {
    Requirement requirement = employerTaskMapper.getRequirementById(taskId);
    Worker worker = employerTaskMapper.getWorkerById(taskId);
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String localDateTime = formatter.format(LocalDateTime.now());
    Recording recording = Recording.builder()
        .recordingContent(
                localDateTime + " 完成" + " '" + requirement.getRequireTitle() + "' 订单,钱包金额+"
                + requirement.getRequireAmount() + "元")
        .recordingType(0)
        .userId(worker.getUserId())
        .build();
    employerTaskMapper.createMoneyRecording(recording);
  }

  /**
   * 发布需求
   *
   * @param taskId
   * @return
   */
  @Override
  public void publishRequire(Long taskId) {
    int credit=employerTaskMapper.getCredit(taskId);
    if(credit<60) {
      throw new BaseException("您的信誉度过低，无法发布");
    }
    int status=employerTaskMapper.getTaskStatusById(taskId);
    if(status!=0) {
      throw new BaseException("只能发布“待付款”的订单");
    }
    employerTaskMapper.publish(taskId);
  }

}
